package run;

import lsieun.utils.FileUtils;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.util.Printer;
import org.objectweb.asm.util.Textifier;
import org.objectweb.asm.util.TraceClassVisitor;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;

public class C_Class_To_Text {
    public static void main(String[] args) {
        String dirPath = PathManager.getClassDir();
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            throw new RuntimeException("Directory Not Exist: " + dirPath);
        }

        String[] fileList = dirFile.list();
        if (fileList == null) {
            System.out.println("There is no File in current Directory: " + dirPath);
            return;
        }

        for (String filename : fileList) {
            if (filename == null) continue;
            if (!filename.endsWith(".class")) continue;

            String filepath = dirPath + File.separator + filename;
            generate(filepath);
        }
    }

    public static void generate(String filepath) {
        // 第一步，创建ClassReader
        byte[] bytes = FileUtils.readBytes(filepath);
        if (bytes == null) return;
        ClassReader cr = new ClassReader(bytes);

        // 第二步，创建ClassVisitor
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        Printer printer = new Textifier();
        PrintWriter printWriter = new PrintWriter(bao, true);
        ClassVisitor cv = new TraceClassVisitor(null, printer, printWriter);

        // 第三步，连接ClassReader和ClassVisitor
        int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
        cr.accept(cv, parsingOptions);

        // 第四步，输出到文件
        String newFilepath = filepath.replace(".class", ".txt");
        FileUtils.writeBytes(newFilepath, bao.toByteArray());
        System.out.println(newFilepath);
    }
}
